import React from 'react';
import PropTypes from 'prop-types';
import Textarea from '../Textarea';

export default function URLTextarea({
	asType,
	value,
	onBlur,
	onChange,
	...props
}) {
	const [text, setText] = React.useState(value.map(decodeURI).join('\n'));
	const prevValue = React.useRef(value);
	React.useMemo(() => {
		if (prevValue.current || !value) return;
		prevValue.current = value;
		setText(value.join('\n'));
	}, [value]);
	const handleChange = e => {
		setText(e.target.value);
		if (asType === 'host') {
			onChange(e.target.value.split('\n').filter(Boolean));
		} else {
			onChange(
				e.target.value
					.split('\n')
					.filter(Boolean)
					.map(x => encodeURI(x.trim()))
			);
		}
	};

	return (
		<Textarea {...props} onChange={handleChange} onBlur={onBlur} value={text} />
	);
}

URLTextarea.propTypes = {
	asType: PropTypes.string,
	className: PropTypes.string,
	value: PropTypes.arrayOf(PropTypes.string),
	onChange: PropTypes.func.isRequired,
	onBlur: PropTypes.func.isRequired,
};

URLTextarea.defaultProps = {
	value: [],
};
